# -*- coding: utf-8 -*-

# graphic-pppoe-client - Easy graphic networking manager
#
# Author: GoTLiuM InSPiRiT <gotlium@gmail.com>
#
# Copyright 2010, GoTLiuM InSPiRiT <gotlium@gmail.com>.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.
from __init__ import *

class BaseModel(object):
	_table = None
	_tblkey = None

	@dbs
	def select(self, id):
		data = db.select(self._table, {self._tblkey: id})
		if data['num'] > 0:
			return data['result']
		return []

	@dbs
	def delete(self, id, data):
		if isinstance(data, list):
			for rid in data:
				db.delete(self._table, {
					self._tblkey: id, 'id': rid
				})
		elif isinstance(data, int):
			db.delete(self._table, {
				self._tblkey: id, 'id': data
			})
		else:
			return False
		return True

	@dbs
	def create(self, id, data):
		if isinstance(data, list):
			ids = []
			for row in data:
				row[self._tblkey] = id
				# TODO: remove when testing done
				print row
				db.insert(self._table, row)
				ids.append(db.insert_id())
		elif isinstance(data, dict):
			data[self._tblkey] = id
			db.insert(self._table, data)
			ids = db.insert_id()
		else:
			return False
		return ids

	@dbs
	def update(self, id, data):
		if isinstance(data, dict):
			db.update(self._table, data, {
				self._tblkey: id, 'id': data['id']
			})
		elif isinstance(data, list):
			for row in data:
				db.update(self._table, row, {
					self._tblkey: id, 'id': row['id']
				})
		else:
			return False
		return True

	def default(self, *args, **kw):
		return False

	def __getattr__(self, name):
		method, table = name[:6], name[6:]
		self._table = table.lower()

		if self._table == 'connections':
			self._tblkey = 'module_id'
		else:
			self._tblkey = 'connection_id'

		try:
			return getattr(self, method)
		except:
			return self.default
